'use strict';

ionicTea.controller('productCtrl', function ($scope, $state,$rootScope,$window,$stateParams,$ionicPopup, $ionicHistory, $ionicModal, HttpService, $ionicLoading, UserService, $ionicSlideBoxDelegate, ShareService) {

	//商品list
	$scope.product_data = [];

	//切换按钮  功能 待封装
	$scope.last_bt = true;
	$scope.hot_bt = "";
	//初始化modal页面
	$ionicModal.fromTemplateUrl('my-modal.html', {
		scope: $scope,
		animation: 'slide-in-up'
	}).then(function (modal) {
		$scope.modal = modal;
	});

	$ionicModal.fromTemplateUrl('./templates/product/product-shop-comment.html', {
        id: 'product-comment',
        scope: $scope,
        animation: 'slide-in-right'
    }).then(function (modal) {
        $scope.product_comment_modal = modal;
    });

    $ionicModal.fromTemplateUrl('./templates/product/store-identify-info.html', {
        id: 'store-identify',
        scope: $scope,
        animation: 'slide-in-right'
    }).then(function (modal) {
        $scope.store_identify_modal = modal;
    });

    $ionicModal.fromTemplateUrl('./templates/product/exc_sample_success.html', {
        id: 'exc-sample-success',
        scope: $scope,
        animation: 'slide-in-right'
    }).then(function (modal) {
        $scope.exc_sample_success_modal = modal;
    });

    //商品点赞什么的 记录下 Id
    $scope.currProduct = {};
    $scope.show_product_comment = function(productId){
    	$scope.currProduct.productId = productId;
    	$scope.product_comment_modal.show();
    };

    $scope.cancel_sample_success = function(){
    	$scope.exc_sample_success_modal.hide();
    };

    $scope.cancel_product_comment = function(){
    	$scope.product_comment_modal.hide();
    };

    //关闭商品认证Modal
    $scope.cancel_store_identify = function(){
    	$scope.store_identify_modal.hide();
    };

	//关闭modal
	$scope.closeModal = function () {
		$scope.modal.hide();
	};

	$scope.productDataInit = function () {
		console.log("开始加载数据");
	};

	/*加载商品分类*/
	$scope.productClass_list;
	$scope.loadProductClass = function () {
		$scope.is_init_last = true;

		//同步加载动画
		$ionicLoading.show({
			template: 'Loading...'
		});

		var callback = {
			success: function success(result) {
				$scope.productClass_list = result;
				console.log("商品分类：");
				console.log($scope.productClass_list);
				//结束加载动画
				$ionicLoading.hide();
				// 停止广播ion-refresher
				$scope.$broadcast('scroll.refreshComplete');
			},
			failed: function failed(err) {
				console.log(err.statusText);
				//结束加载动画
				$ionicLoading.hide();
				// 停止广播ion-refresher
				$scope.$broadcast('scroll.refreshComplete');
			}
		};

		HttpService({ name: 'product/category/list', params: {}, callback: callback });

		$scope.loadHotProduct();
	};

	//请求  商品列表
	$scope.currPage_last = 1;
	$scope.currPage_hot = 1;
	$scope.currPage = 1;

	$scope.load_product_list = function (param) {

		var user = UserService.getUserAcceptCache();
		if (!user) return;

		//同步加载动画
		$ionicLoading.show({
			template: 'Loading...'
		});
		param.user_id = user.id;

		console.log("查询商品 条件："+JSON.stringify(param));

		var callback = {
			success: function success(result) {
				//$scope.product_data = result.result;
				var data = result.result;
				var length = data.length;
				if(length == 0){
					$scope.isStop_scroll = true;
					return;
				}

				for(var i=0;i<length;i++){
					$scope.product_data.push(data[i]);
				}

				if($scope.is_init_last){
					$scope.isStop_scroll = false;
				}

				console.log("加载完毕");
				console.log($scope.product_data);
				//结束加载动画
				$ionicLoading.hide();
				$scope.$broadcast('scroll.infiniteScrollComplete');
				// 停止广播ion-refresher
				$scope.$broadcast('scroll.refreshComplete');
			}
		};

		HttpService({ name: 'product/list', params: param, callback: callback });
	};

	//初始化最新页面
	$scope.is_init_last = true;

	/*加载最新产品*/
	$scope.loadLastProduct = function () {
		$scope.product_data = [];
		$scope.currPage = 1;
		$scope.is_init_last = true;

		$scope.last_bt = true;
		$scope.hot_bt = false;
		var param = {
			page: $scope.currPage
		};

		if($stateParams.isSearch){
			$scope.product_data = $stateParams.product_search;
			$stateParams.isSearch = false;
			$scope.pick_param.keyword = $stateParams.keyword;
		}else{
			$scope.load_product_list(param);
		}
	};

	/*加载最热产品*/
	$scope.loadHotProduct = function () {
		$scope.product_data = [];
		$scope.hot_bt = true;
		$scope.last_bt = false;
		$scope.currPage = 1;
		$scope.is_init_last = true;

		var param = {
			page: $scope.currPage,
			orderby: 'hot'
		};
		$scope.load_product_list(param);
	};

	/*滚动加载商品*/
	$scope.scrollCfg = {
		isScroll: false
	};

	$scope.isStop_scroll = true;

	$scope.scroll_load_product = function () {
		$scope.currPage += 1;
		if($scope.hot_bt){
			var param = {
				page: "'"+$scope.currPage+"'",
				orderby: 'hot'
			};
		}else{
			var param = {page: ''+$scope.currPage};
		}
		if($scope.pick_param.keyword)param.keyword = $scope.pick_param.keyword;
		$scope.load_product_list(param);
	};
	/*$scope.$on('stateChangeSuccess', function() {
	    $scope.scroll_load_product();
	});*/


	/*淘茶分类页面数据初始化*/
	$scope.className = '';
	$scope.product_class_Init = function () {
		$scope.isStop_scroll = true;
		$scope.is_init_last = true;
		$scope.currPage = 1;
		//$scope.currPage_normal = '1';
		$scope.className = $stateParams.className;
		$scope.load_product_class();
	};

	/*按分类加载商品*/
	$scope.load_product_class = function () {
		var param = {
			page: $scope.currPage_normal,
			category_id: $stateParams.classId
		};
		$scope.load_product_list(param);
	};

	//滚动加载分类
	$scope.scroll_load_product_class = function(){

		$scope.currPage += 1;

		var param = {
			page: $scope.currPage,
			category_id: $stateParams.classId
		};
		$scope.load_product_list(param);
	}

	/*商品筛选*/
	$scope.pick_param = {name:''};
	$scope.product_pick = function(){
		console.log("帅选商品参数："+JSON.stringify($scope.pick_param));
		//同步加载动画
		$ionicLoading.show({
			template: 'Loading...'
		});

		var param = $scope.pick_param;
		param.page = '1';

		var callback = {
			success: function success(result) {
				console.log("商品筛选返回：");
				console.log(result);
				$state.go('product-search', { product_list: result.result,pick_param: param});

				//结束加载动画
				$ionicLoading.hide();
			},
			failed: function failed(err) {
				console.log(err.statusText);
				//结束加载动画
				$ionicLoading.hide();
			}
		};

		HttpService({ name: 'product/search', params: param, callback: callback });
	}

	//商品筛选(搜索)请求
	$scope.product_pick_http = function(param){
		//同步加载动画
		$ionicLoading.show({
			template: 'Loading...'
		});
		console.log("搜索条件："+JSON.stringify(param));
		var callback = {
			success: function success(result) {
				console.log("商品搜索返回：");
				console.log(result);
				$scope.product_data = result.result;
				//结束加载动画
				$ionicLoading.hide();
			},
			failed: function failed(err) {
				console.log(err.statusText);
				//结束加载动画
				$ionicLoading.hide();
			}
		};
		HttpService({ name: 'product/search', params: param, callback: callback });
	}

	//商品搜索页面初始化
	$scope.product_search_init = function(){
		$scope.pick_param = $stateParams.pick_param;
		$scope.product_data = $stateParams.product_list;
	}

	//商品搜索
	$scope.product_search = function(e){
		var keycode = window.event?e.keyCode:e.which;
		var name = e.target.value;
        if(keycode==13){
        	var param = {
        		name: $scope.pick_param.name,
        		page: '1'
        	};
            $scope.product_pick_http(param);
            e.target.value = '';
        }
	}

	//关闭筛选结果modal
	$scope.back_pick = function(){
		$rootScope.back();
	}

	//重置筛选
	$scope.reset_pick = function(){
		$scope.pick_param = {};
	}

	/*只允许输入数字*/
	$scope.onlyNum = function(event){
		var dom = event.target;
		var text = dom.value;
		var reg = new RegExp("^[0-9]*$");
		if(!reg.test(text)){
			dom.value = '';
		}
	}

	//初始化活动
	$scope.ac_time = true;
	$scope.ac_hot = false;
	$scope.activityInit = function(){
		$scope.isStop_scroll = true;
		$scope.currPage = 1;

		var param = {
			page:'1'
		};
		$scope.loadActivity(param);
	}
	//分类活动
	$scope.load_act_type = function(type){
		if(type == 'time'){
			$scope.ac_time = true;
			$scope.ac_hot = false;
		}else{
			$scope.ac_time = false;
			$scope.ac_hot = true;
		}
		$scope.currPage = 1;
		var param = {
			page:'1',
			orderby:type
		};
		$scope.loadActivity(param);
	}

	$scope.ac_fresh = function(){
		var param = {};
		$scope.currPage = 1;
		if($scope.ac_time){
			param = {
				page:'1',
				orderby:'time'
			};
		}else{
			param = {
				page:'1',
				orderby:'hot'
			};
		}
		$scope.loadActivity(param);
	};

	/**活动商品*/
	$scope.loadActivity = function(param){

		var callback = {
			success: function success(result) {
				console.log("加载活动商品：");
				console.log(result);
				$scope.isStop_scroll = false;
				$scope.product_data = result.result;
				$scope.$broadcast('scroll.refreshComplete');
			}
		};

		HttpService({ name: 'product/activity', params: param, callback: callback });
	};

	//滚动加载活动
	$scope.scroll_load_ac = function(){
		$scope.currPage += 1;

		var param = {
			page: $scope.currPage,
			orderby: $scope.ac_time?"time":"hot"
		};
		console.log("滚动  加载活动商品："+JSON.stringify(param));

		var callback = {
			success: function success(result) {
				console.log("加载活动商品：");
				console.log(result);
				var length = result.result;
				if(length == 0){
					$scope.isStop_scroll = true;
					return;
				}
				for(var i=0;i<length;i++){
					$scope.product_data.push(result.result[i]);
				}
				$scope.$broadcast('scroll.refreshComplete');
				$scope.$broadcast('scroll.infiniteScrollComplete');
			}
		};

		HttpService({ name: 'product/activity', params: param, callback: callback });
	}

	//跳转商品详情
	$scope.goto_product_info = function (id) {
		$state.go('product-info', { product_id: id });
	};

	//商品明细
	$scope.productInfo = {};
	$scope.info_img_list = [];
	$scope.loadProductInfo = function () {

		var param = {product_id: $stateParams.product_id};
		var user = UserService.getUserAcceptCache();
		if (user) param.user_id = user.id;

		var callback = {
			success: function success(result) {
				$scope.productInfo = result;
				$ionicSlideBoxDelegate.update();
				$ionicSlideBoxDelegate.$getByHandle('product_slideimgs').loop(true);

				$scope.flag1 = !(result.certificate.indexOf('1') == -1);
				$scope.flag2 = !(result.certificate.indexOf('2') == -1);
				$scope.flag3 = !(result.certificate.indexOf('3') == -1);
				$scope.flag4 = !(result.certificate.indexOf('4') == -1);

				//把图片处理成插件所需的格式
				var imgs = result.imglist;
				var length = imgs.length;
				if(length == 0)return;
				var items = [];
				for(var img in imgs){
					console.log("图片链接："+imgs[img]);
					var item = {
						src:imgs[img],
						thumb:imgs[img]
					};
					items.push(item);
				}
				console.log("格式转换后："+JSON.stringify(items));
				$scope.info_img_list = items;
			},
			failed: function failed(err) {
				console.log(err.statusText);
			}
		};

		HttpService({ name: 'product/show', params: param, callback: callback });
		$scope.loadComments();
	};

	//商品评论
	$scope.currPage_comment = 1;
	$scope.comments = [];
	$scope.comments_count = 0;
	$scope.loadComments = function () {
		$scope.currPage_comment = 1;

		var callback = {
			success: function success(result) {
				console.log("加载商品评论：");
				console.log(result);
				$scope.comments_count = result.count;
				$scope.comments = result.result;
			},
			failed: function failed(err) {
				console.log(err.statusText);
			}
		};

		var param = {
			product_id:$stateParams.product_id,
			page:$scope.currPage_comment
		};

		HttpService({ name: 'product/comment/list', params: param, callback: callback });
	};

	$scope.load_product_comment = function(){
		$scope.currPage_comment += 1;

		var callback = {
			success: function success(result) {
				console.log("加载商品评论：");
				console.log(result);
				$scope.comments_count = result.count;
				var length = result.result.length;
				for(var i=0;i<length;i++){
					$scope.comments.push(result.result[i]);
				}
			},
			failed: function failed(err) {
				console.log(err.statusText);
			}
		};

		var param = {
			product_id:$stateParams.product_id,
			page:$scope.currPage_comment
		};

		HttpService({ name: 'product/comment/list', params: param, callback: callback });
	}


	//商品详情进入店铺
	$scope.product_goto_store = function () {

		$state.go('store', { store_id: $scope.productInfo.shop.id }, { reload: true });
	};

	//从淘茶进入商品评论
	$scope.tao_to_product_com = function(productId){

	}

	//商品评论
	$scope.product_comment = {content:''};
	$scope.sent_product_comment = function(){
		var user = UserService.getUserAcceptCache(true);
		if (!user) return;
		var param = {
			user_id: user.id,
			product_id: $scope.currProduct.productId,
			content: $scope.product_comment.content
		};
		console.log("商品评论参数："+JSON.stringify(param));
		var callback = {
			success: function success(result) {
				console.log("发布商品评论 返回值：");
				console.log(result);
				$scope.loadComments();
				$scope.cancel_product_comment();
				$scope.product_comment.content = '';
			},
			failed: function failed(err) {
				console.log(err.statusText);
			}
		};

		HttpService({ name: 'product/comment/create', params: param, callback: callback });
	}

	//收藏商品
	$scope.product_isFollow = false;
	$scope.product_follow = function () {
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var callback = {
			success: function success(result) {
				console.log("收藏商品：");
				console.log(result);
				if(result.code == 200){
					$scope.productInfo.is_followed = true;
					$scope.product_follow_alert();
				}

			}
		};

		HttpService({ name: 'product/follow', params: { product_id: $stateParams.product_id, user_id: user.id }, callback: callback });
	};

	//提示已收藏商品
	$scope.product_follow_alert = function(){
     	var alertPopup = $ionicPopup.alert({
	       	template: '<p class="text-center alert-img"><img src="img/4title/last.png"/></p>'+
	       			  '<p class="text-center alert-label">已添加</p>'+
	       			  '<p class="text-center alert-content">客官已添加到商品收藏中</p>',
	       	okText: '收藏成功',
	       	okType: 'button-balanced'
     	});
     	alertPopup.then(function(res) {
       		console.log('Thank you for not eating my delicious ice cream cone');
     	});
	}

	//取消收藏提示
	$scope.follow_cancel_alert = function(){
     	var alertPopup = $ionicPopup.alert({
	       	template: '<p class="text-center alert-img"><img src="img/4title/last.png"/></p>'+
	       			  '<p class="text-center alert-label">已取消收藏</p>',
	       	okText: '取消收藏',
	       	okType: 'button-balanced'
     	});
     	alertPopup.then(function(res) {
       		console.log('Thank you for not eating my delicious ice cream cone');
     	});
	}

	//取消收藏商品
	$scope.product_follow_cancel = function () {
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var callback = {
			success: function success(result) {
				console.log("取消收藏商品：");
				console.log(result);
				if(result.code == 200){
					$scope.productInfo.is_followed = false;
					$scope.follow_cancel_alert();
				}

			}
		};

		HttpService({ name: 'product/follow/cancel', params: { product_id: $stateParams.product_id, user_id: user.id }, callback: callback });
	};

	$scope.is_vote = function(isUpvote,productId){
		if(isUpvote){
			$scope.upvote_cancel(productId);
		}else{
			$scope.upvote(productId);
		}
	}

	//商品点赞
	$scope.upvote = function(productId){
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var param = {
			product_id: productId,
			user_id: user.id
		}
		console.log("商品点赞参数："+JSON.stringify(param));

		var callback = {
			success: function success(result) {
				console.log("商品点赞：");
				console.log(result);
				$scope.productInfo.is_upvote = true;
				$scope.productInfo.upvote_count += 1;
				if(result.code == '200'){
					var length = $scope.product_data.length;
					for(var i=0;i<length;i++){
						 if($scope.product_data[i].id == productId){
						 	$scope.product_data[i].is_upvote = true;
						 	$scope.product_data[i].upvote_count += 1;
						 }
					}
				}
			},
			failed:function(msg){
				console.log("点赞失败返回："+msg);
			}

		};

		HttpService({ name: 'product/upvote', params: param, callback: callback });
	}


	//取消点赞
	$scope.upvote_cancel = function(productId){
		var user = UserService.getUserAcceptCache();
		if (!user) return;
		var param = {
			product_id:productId,
			user_id:user.id
		}
		console.log("商品点赞参数："+JSON.stringify(param));

		var callback = {
			success: function success(result) {
				console.log("商品点赞取消：");
				console.log(result);
				$scope.productInfo.is_upvote = false;
				$scope.productInfo.upvote_count -= 1;
				if($scope.productInfo.upvote_count < 0 )$scope.productInfo.upvote_count = 0;
				var length = $scope.product_data.length;
				for(var i=0;i<length;i++){
					 if($scope.product_data[i].id == productId){
					 	$scope.product_data[i].is_upvote = false;
					 	$scope.product_data[i].upvote_count -= 1;
					 	if($scope.product_data[i].upvote_count < 0)$scope.product_data[i].upvote_count = 0;
					 }
				}
			}
		};

		HttpService({ name: 'product/upvote/cancel', params: param, callback: callback });
	}

	//茶样兑换
	$scope.sample_param = {};
	$scope.sample_exc = function(){
		// 一个精心制作的自定义弹窗
	   	var myPopup = $ionicPopup.show({
	     	template: '<input type="text" ng-model="sample_param.num" placeholder="输入茶样兑换数量">',
	     	title: '<p class="font-color-green text-center">积分兑换茶样</p>',
	     	subTitle: '<p class="font-color-gray text-center">兑换后将扣去相应积分</p>',
	     	scope: $scope,
	     	buttons: [
		        { text: '取消' },
		        {
		         	text: '<b>兑换</b>',
		         	type: 'button-positive',
		         	onTap: function(e) {
		         		if(!$scope.sample_param.num){
		         			$rootScope.alert_err("请输入兑换的件数");
		         			return;
		         		}
		         		$scope.sample_http($scope.productInfo.id,$scope.sample_param.num);
		         	}
	       		},
	     	]
	   	});
	}

	//茶样兑换接口
	$scope.sample_http = function(productId,num){
		var user = UserService.getUserAcceptCache();
		if (!user) return;
		var param = {
			product_id:productId,
			user_id:user.id,
			number: num
		}
		console.log("茶样兑换参数："+JSON.stringify(param));

		var callback = {
			success: function success(result) {
				console.log("茶样兑换返回：");
				console.log(result);
				if(result.code == 200){
					$scope.exc_sample_success_modal.show();
				}
			}
		};

		HttpService({ name: 'product/sample/exchange', params: param, callback: callback });
	}

	$scope.share = function () {
		ShareService.shareImgMsg($scope.productInfo.name, $scope.productInfo.imglist);
	};

	$scope.shareOfflineShop = function () {
		ShareService.shareImgMsg($scope.storeInfo.name, $scope.storeInfo.logo);
	};
	//立即购买
	$scope.buyInfo = { count: 1 };
	$scope.buy = function () {
		$scope.modal.show();
	};

	var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

    function generateMixed(n) {
         var res = "";
         for(var i = 0; i < n ; i ++) {
             var id = Math.ceil(Math.random()*35);
             res += chars[id];
         }
         return res;
    }

		$scope.createOrder = function() {
			if ($scope.pay_info.type != 1) {
				alert('目前暂时只开通了支付宝支付，微信支付暂时还未开通!');
				return;
			}

			var user = UserService.getUserAcceptCache(true);

			var callback = {
				success: function(data) {
					//第一步：订单在服务端签名生成订单信息，具体请参考官网进行签名处理
				     var payInfo  = data.paystr;

				     // payInfo = encodeURI(payInfo);

				     // payInfo = 'app_id=2015052600090779&biz_content=%7B%22timeout_express%22%3A%2230m%22%2C%22seller_id%22%3A%22%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.01%22%2C%22subject%22%3A%221%22%2C%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%22IQJZSRC1YMQB5HU%22%7D&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=http%3A%2F%2Fdomain.merchant.com%2Fpayment_notify&sign_type=RSA&timestamp=2016-08-25%2020%3A26%3A31&version=1.0&sign=cYmuUnKi5QdBsoZEAbMXVMmRWjsuUj%2By48A2DvWAVVBuYkiBj13CFDHu2vZQvmOfkjE0YqCUQE04kqm9Xg3tIX8tPeIGIFtsIyp%2FM45w1ZsDOiduBbduGfRo1XRsvAyVAv2hCrBLLrDI5Vi7uZZ77Lo5J0PpUUWwyQGt0M4cj8g%3D';

					 // payInfo = 'body=teststst&notify_url=http://211.149.220.47/php/notify_url.php&out_trade_no=47650156447157&partner=2088421497453692&seller=2088421497453692&subject=test&total_fee=1.00&sign=rGK%2Bbg1R0S6Bi9eQ5DoFHF2OH4EYCTmSceq7A2DMjz8Pz5V9UW%2F79CJphZjue0c7w8%2F1JD7F%2B09G%2FeK%2FtdO1TOgt9RTyJsFUzSsSpjqdzkaBo68ym%2FU4zWuCe%2B8rtxIQaS1xR37B1aCA%2Be8JuCd4Ka4EO3u8yp9kxgGGTVEPsUw%3D&sign_type=RSA';
					 payInfo = '_input_charset=utf-8&body=test&it_b_pay=30m&notify_url=http://211.149.220.47/php/notify_url.php&out_trade_no=47712134674673&partner=2088421497453692&payment_type=1&seller_id=3463229464@qq.com&service=mobile.securitypay.pay&subject=test&total_fee=0.01&sign="ORJK7aT%2F%2FOAz5NGjCtBW7AU3Ld7gygCLPLLQ2bQI42iyAwYj7e1ps8c3Oa8%2FI07eGSL7rpIMdIG6KN3DK2ANEzL8pmS4%2BmBiVw%2BEiXtA2cXDfRm63FZcDWk%2FQCL4OyhBcQuDT6LqkwsDxH03Nu8sC7JikHP7%2BLPT9VudyMz0pMk%3D"&sign_type="RSA"';
				     console.log(payInfo);

				     // payInfo = encodeURI(payInfo);

				    //第二步：调用支付插件
				     cordova.plugins.AliPay.pay(payInfo,function success(e){
				     	alert(JSON.stringify(e));
				     },function error(e){
				     	alert(JSON.stringify(e));
				     });

				    //e.resultStatus  状态代码  e.result  本次操作返回的结果数据 e.memo 提示信息
				    //e.resultStatus  9000  订单支付成功 ;8000 正在处理中  调用function success
				    //e.resultStatus  4000  订单支付失败 ;6001  用户中途取消 ;6002 网络连接出错  调用function error
				    //当e.resultStatus为9000时，请去服务端验证支付结果
				                /**
				                 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				                 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				                 * docType=1) 建议商户依赖异步通知
				                 */
				},
				failed: function() {

				},
			};

			var products = [];
			for (var pos=0; pos<$scope.orderInfo.products.length;pos++) {
				products.push({
					id: $scope.orderInfo.products[pos].id,
					number: $scope.orderInfo.products[pos].count,
				});
			}

			HttpService({ name: 'order/create',
				params: {
					user_id: user.id,
					products: JSON.stringify(products),
				 	paytype: $scope.pay_info.type == 1? 'alipay' : 'weixin',
				}, callback: callback });
		}

    // $scope.pay = function() {
    //     var appid = 'wx7f06d3ea403df9fa';
    //     var appkey = '6b7364740c4fc8c814f6099dabaa7e37';
    //     var mch_id = '1361228902';
    //     var nonce_str = generateMixed(18);
    //     var timestamp = (new Date()).getTime();
    //     var prepayid = 'wx'.concat(generateMixed(16));
		//
    //     console.log('prepayid = ' + prepayid);
		//
    //     var stringA = 'appid='.concat(appid).concat('&body=test&device_info=1000&mch_id=').concat(mch_id).concat('&nonce_str=').concat(nonce_str);
    //     var stringSignTemp = stringA.concat("&key=").concat(appkey);
		//
    //     console.log('stringSignTemp = ' + stringSignTemp);
		//
    //     var sign = md5(stringSignTemp).toUpperCase();
		//
    //     console.log('sign = ' + sign);
		//
    //     var params = {
    //        partnerid: mch_id, // merchant id
    //        prepayid: prepayid, // prepay id
    //        noncestr: nonce_str, // nonce
    //        timestamp: timestamp, // timestamp
    //        sign: sign, // signed string
    //     };
		//
    //     Wechat.sendPaymentRequest(params, function () {
    //        alert("Success");
    //     }, function (reason) {
    //        alert("Failed: " + reason);
    //     });
    // };

	//加入购物车
	$scope.addCart = function () {
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var callback = {
			success: function success(result) {
				console.log("加入购物车：");
				console.log(result);
				$rootScope.alert_suc("已加入购物车");
			}
		};

		HttpService({ name: 'shopcart/add', params: { product_id: $stateParams.product_id, user_id: user.id }, callback: callback });
	};

	//跳转确认订单
	$scope.orderInfo = {};
	$scope.isNotFromCart = true;
	$scope.goto_orderConfirm = function () {
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		$scope.modal.hide();
		//设置商品购买信息
		var product = $scope.productInfo;
		$scope.buyInfo = {
			count: $scope.buyInfo.count,
			id: product.id,
			name: product.name,
			sale_price: product.sale_price,
			shop_logo: product.shop.logo,
			shop_name: product.shop.name
		};

		var orderInfo = {
			userInfo: null,
			products: [$scope.buyInfo]
		};
		console.log(" 订单检查：");console.log(orderInfo);
		//记得穿参数
		$state.go("product-orderConfirm", { from_url: 'product-info', orderInfo: orderInfo });

		//初始化modal页面
		$ionicModal.fromTemplateUrl('my-modal.html', {
			scope: $scope,
			animation: 'slide-in-up'
		}).then(function (modal) {
			$scope.modal = modal;
		});
	};

	function calcCount() {
		//计算下辣鸡合计
		var products = $scope.orderInfo.products;
		var all = 0;
		for (var i = 0; i < products.length; i++) {
			all += products[i].count * products[i].sale_price;
		}
		$scope.orderInfo.count_price = all;
	};

	//确认订单初始化
	$scope.orderInit = function () {
		$scope.orderInfo = $stateParams.orderInfo;
		var backURL = $stateParams.from_url;
		if ('product-info' == backURL) {
			$scope.backURL = $stateParams.from_url;
			$scope.isNotFromCart = true;
		} else {
			$scope.isNotFromCart = false;
		}

		// 地址为空就用默认地址
		if ($stateParams.orderInfo.userInfo == null) {
			var user = UserService.getUserAcceptCache();

			var callback = {
				success: function success(data) {
					// 显示地址列表
					var length = data.length;
					for(var pos=0;pos<length;pos++) {
						if(data[pos].default == true) {
							var userInfo = {
								realname: data[pos].name,
								mobile: data[pos].mobile,
								address: data[pos].province.name + " " + data[pos].city.name + " " + data[pos].county.name + " " + data[pos].address
							};
							$scope.orderInfo.userInfo = userInfo;
						}
					}
				},
				failed: function failed(err) {}
			};

			HttpService({ name: 'user/address/list', params: { user_id: user.id }, callback: callback });
		}

		//设置监听
		$scope.$watch('orderInfo', calcCount, true);
	};

	//提交订单
	$scope.submit_order = function () {
		$scope.modal.show();
	};

	//弹出选择付款方式    1： 支付宝     2：微信
	$scope.pay_info = {type:1};
	$scope.pay_type = function(){
		var myPopup = $ionicPopup.show({
		    template: '<div class="list ">'+
		    		  '<ion-radio ng-value="1" ng-model="pay_info.type"><p>支付宝</p></ion-radio><ion-radio ng-value="2" ng-model="pay_info.type"><p>微信</p></ion-radio>'+
		    		  '</div>',
		    title: '选择付款方式',
		    scope: $scope,
		    buttons: [
		       	{ text: '取消' },
		       	{
		         	text: '<b>确定</b>',
		         	type: 'button-positive',
		         	onTap: function(e) {
		         		//$scope.pay_info
		         		//alert($scope.pay_info.type);
		         	}
		     	},
		     ]
		});

	}

	$scope.goToChooseAddress = function () {
		$state.go('setting-address', { isChooseAddress: true, orderInfo: $scope.orderInfo, from_url: 'product-info' });
	};

	//确认订单页面返回
	$scope.orderConfirm_back = function () {
		if ($scope.isNotFromCart) {
			var product_id = $scope.orderInfo.products[0].id;
			$state.go($scope.backURL, { product_id: product_id });
		} else {
			$rootScope.back();
		}

	};

	$scope.updateProduct = function () {

		if ($scope.last_bt) {
			$scope.loadLastProduct();
		} else {
			$scope.loadHotProduct();
		}

		// 停止广播ion-refresher
		$scope.$broadcast('scroll.refreshComplete');
	};

	//跳转商家认证
	$scope.goto_storeIdenty = function () {
		$state.go('store-identy',{storeInfo:$scope.storeInfo});
	};

	$scope.identyInit = function(){
		$scope.storeInfo = $stateParams.storeInfo;
	};

	$scope.shareStore = function() {
		ShareService.shareImgMsg($scope.storeInfo.name, $scope.storeInfo.imglist);
	}

	//淘茶
	$scope.goto_product_class = function (classId,className) {
		$state.go("product-class", { classId: classId,className:className });
	};

	//淘茶分类跳转筛选页面
	$scope.class_goto_pick = function () {
		//存储放回标志
		sessionStorage.setItem("product-pick-flag", "product-class");
		$state.go("product-pick");
	};

	//最新商品跳转筛选页面
	$scope.last_goto_pick = function () {
		//存储放回标志
		sessionStorage.setItem("product-pick-flag", "product-last");
		$state.go("product-pick");
	};

	//商品筛选初始化
	$scope.year_list = [];
	$scope.product_pick_init = function(){
		var curYear = parseInt(new Date().getFullYear());
		var startYear = 1900;

		for(var i=startYear;i<=curYear;i++){
			$scope.year_list.push(i);
		}
	}

	//从筛选页面返回
	$scope.product_pick_back = function () {

		var goPath = sessionStorage.getItem("product-pick-flag");
		$state.go(goPath);
	};

	//跳转线下店铺页面
	//$scope.underLine_list = [];
	$scope.goto_underLine = function () {
		$state.go("store-underLine",{storeInfo:$scope.storeInfo});
	};

	$scope.underInit = function(){
		$scope.storeInfo = $stateParams.storeInfo;
	}

	$scope.back_from = function () {
		$rootScope.back();
	};

	//跳转客服
	$scope.product_goto_chat = function(id){
		$state.go("chat",{id: id});
	}


	/*--------店铺列表----------------------------------------------------------------------------------------------------------*/

	//收藏店铺
	$scope.isfollow = "收藏店铺";

	$scope.storeData = [];
	$scope.storeTab_info = '';
	$scope.store_tab = [{name:'简介',id:"store_tab1"},{name:'企业文化',id:"store_tab2"},{name:'产地',id:"store_tab3"},{name:'联系方式',id:"store_tab4"}];
	//初始化店铺列表
	$scope.store_list_init = function(){
		$scope.currPage = 1;
		$scope.isStop_scroll = true;

		if($stateParams.isSearch){
			$scope.store_search_info.keyword = $stateParams.keyword;
			$scope.storeData = $stateParams.store_list;
			$scope.isStop_scroll = false;
		}else{
			$scope.loadStoreList();
		}
	}

	//加载店铺列表
	$scope.loadStoreList = function () {
		//获取数据
		var storeCallback = {
			success: function success(result) {
				$scope.storeData = result.result;
				$scope.isStop_scroll = false;
				console.log($scope.storeData);
			},
			failed: function failed(err) {

			}
		};

		HttpService({ name: 'shop/list', params: { page: $scope.currPage }, callback: storeCallback });
	};

	//滚动加载店铺
	$scope.scroll_load_store = function () {

		$scope.currPage += 1;

		var param = {
			page: $scope.currPage,
			keyword:$scope.store_search_info.keyword
		};

		console.log("执行了 滚动加载店铺："+JSON.stringify(param));
		//获取数据
		var storeCallback = {
			success: function success(result) {
				var length = result.result.length;
				if(length == 0){
					$scope.isStop_scroll = true;
					return;
				}
				for(var i=0;i<length;i++){
					$scope.storeData.push(result.result[i]);
				}
				$scope.$broadcast('scroll.infiniteScrollComplete');
			},
			failed: function failed(err) {
				console.log(err.statusText);
			}
		};

		HttpService({ name: 'shop/list', params: param, callback: storeCallback });
	}

	$scope.store_tab_change = function(tabId){
		var def_str = '店家比较懒，没有填写相关信息';
		switch(tabId){
			case 'store_tab1':{
				$scope.storeTab_info = $scope.storeInfo.description==''?def_str:$scope.storeInfo.description;
				break;
			}
			case 'store_tab2':{
				$scope.storeTab_info = $scope.storeInfo.culture==""?def_str:$scope.storeInfo.culture;
				break;
			}
			case 'store_tab3':{
				$scope.storeTab_info = $scope.storeInfo.culture==''?def_str:$scope.storeInfo.production_addr;
				break;
			}
			case 'store_tab4':{
				$scope.storeTab_info = $scope.storeInfo.contact==''?def_str:$scope.storeInfo.contact;
				break;
			}
		}
	};

	//店铺列表页面返回
	$scope.back_tab_main = function () {
		$state.go('tab.main');
	};

	/**店铺搜索初始化*/
	$scope.search_store_init = function(){
		var cache = localStorage.getItem("store-search-data");
		$scope.store_search_info.keyword = '';
		if(cache){
			$scope.store_search_info.lastSearch = JSON.parse(cache);
		}
	}

	//跟句搜索记录 搜索
	$scope.cache_search = function(keyword){
		$scope.store_search_info.keyword = keyword;
		$scope.search_store();
	}

	//清除搜索记录
	$scope.clear_search_cache = function(){
		localStorage.removeItem("store-search-data");
		$scope.store_search_info.lastSearch = [];
	}

	/*店铺搜索*/
	$scope.store_search_info = {lastSearch:[],hotSearch:[]};
	$scope.search_store = function(){
		if($scope.store_search_info.keyword == '')return;

		var param = {
			keyword:$scope.store_search_info.keyword,
			page:$scope.currPage_normal
		}

		//保存最近搜索
		var cache = localStorage.getItem("store-search-data");

		if(cache){
			cache = JSON.parse(cache);
			//有的 删掉，放最前面
			var length = cache.length;
			for(var i=0;i<length;i++){
				if(cache[i] == param.keyword){
					cache.splice(i,1);
				}
			}
		}else{
			cache = [];
		}
		cache.push(param.keyword);
		localStorage.setItem("store-search-data",JSON.stringify(cache));

		var storeCallback = {
			success: function success(result) {
				console.log("搜索店铺：");console.log(result);
				/*$scope.store_search_info.keyword = '';*/
				if(result.result.length > 0){
					$state.go('store-list', {isSearch: true,store_list: result.result,keyword:param.keyword});
				}else{
					$rootScope.alert_msg("没有搜索结果");
				}
			}
		};
		HttpService({ name: 'shop/list', params: param, callback: storeCallback });
	};


	//店铺明细
	$scope.storeInfo;

	//进入店铺
	$scope.gotoStore = function (id) {

		$state.go('store', { store_id: id }, { reload: true });
	};

	//每次进入店铺首页刷新数据，
	$scope.loadStoreInfo = function () {

		var user = UserService.getUserAcceptCache();
		var param = {shop_id: $stateParams.store_id};

		if (user) param.user_id = user.id;
		//同步加载动画
		$ionicLoading.show({
			template: 'Loading...'
		});

		//获取店铺明细
		var storeCallback = {
			success: function success(result) {
				$scope.storeInfo = result;
				$scope.product_data = $scope.storeInfo.product_lists;
				console.log("加载完毕");
				console.log($scope.storeInfo);
				//结束加载动画
				$ionicLoading.hide();
				$ionicSlideBoxDelegate.update();
				$ionicSlideBoxDelegate.$getByHandle('slideimgs').loop(true);
			},
			failed: function failed(err) {
				console.log(err.statusText);
				//结束加载动画
				$ionicLoading.hide();
			}
		};

		HttpService({ name: 'shop/show', params: param, callback: storeCallback });
	};

	//收藏店铺
	$scope.follow_store = function (storeId) {
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var callback = {
			success: function success(result) {
				console.log("收藏店铺返回结果：");
				console.log(result);
				if(result.code == '200'){
					$scope.storeInfo.is_followed = true;
					$scope.storeInfo.follow_count += 1;
					$scope.store_follow_alert();
				}
			}
		};

		HttpService({ name: 'shop/follow', params: { shop_id: storeId, user_id: user.id }, callback: callback });
	};

	//提示已收藏店铺
	$scope.store_follow_alert = function(){
     	var alertPopup = $ionicPopup.alert({
	       	template: '<p class="text-center alert-img"><img src="img/4title/last.png"/></p>'+
	       			  '<p class="text-center alert-label">已添加</p>'+
	       			  '<p class="text-center alert-content">客官已添加到店铺收藏中</p>',
	       	okText: '收藏成功',
	       	okType: 'button-balanced'
     	});
     	alertPopup.then(function(res) {
       		console.log('Thank you for not eating my delicious ice cream cone');
     	});
	}


	//取消收藏店铺
	$scope.cancel_follow_store = function (storeId) {
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var callback = {
			success: function success(result) {
				console.log("取消收藏店铺返回结果：");
				console.log(result);
				if(result.code == '200')
				$scope.storeInfo.is_followed = false;
				$scope.storeInfo.follow_count -= 1;
				if($scope.storeInfo.follow_count < 0)$scope.storeInfo.follow_count = 0;
				$scope.follow_cancel_alert();
			}
		};

		HttpService({ name: 'shop/follow/cancel', params: { shop_id: storeId, user_id: user.id }, callback: callback });
	};

	//店铺点赞
	$scope.store_upvote = function(storeId){
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var callback = {
			success: function success(result) {
				console.log("店铺点赞返回结果：");
				console.log(result);
				if(result.code == '200'){
					$scope.storeInfo.is_upvote = true;
				}
			}
		};

		HttpService({ name: 'shop/upvote', params: { shop_id: storeId, user_id: user.id }, callback: callback });
	}

	//店铺取消点赞
	$scope.store_upvote_cancel = function(storeId){
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var callback = {
			success: function success(result) {
				console.log("取消店铺点赞返回结果：");
				console.log(result);
				if(result.code == '200'){
					$scope.storeInfo.is_upvote = false;
				}
			}
		};

		HttpService({ name: 'shop/upvote/cancel', params: { shop_id: storeId, user_id: user.id }, callback: callback });
	}

	/*店铺评论列表*/
	$scope.store_comments = [];
	$scope.store_comment_count = 0;
	$scope.load_store_comments = function (storeId) {
		var callback = {
			success: function success(result) {
				console.log("店铺评论返回：");
				console.log(result);
				$scope.store_comment_count = result.count;
				$scope.store_comments = result.result;
				$scope.isStop_scroll = false;
			}
		};

		HttpService({ name: 'shop/comment/list', params: { shop_id: storeId, page: '1' }, callback: callback });
	};

	//店铺评论分页
	$scope.curr_store_id = '';
	$scope.scroll_load_store_comments = function(){
		$scope.currPage += 1;

		var param = {
			page: $scope.currPage,
			shop_id: $scope.curr_store_id
		};

		var callback = {
			success: function success(result) {
				console.log("店铺评论返回：");
				console.log(result);
				$scope.store_comment_count = result.count;
				var length = result.result.length;
				if(length == 0){
					$scope.isStop_scroll = true;
					return;
				}
				for(var i=0;i<length;i++){
					$scope.store_comments.push(result.result[i]);
				}
				$scope.$broadcast('scroll.infiniteScrollComplete');
			}
		};

		HttpService({ name: 'shop/comment/list', params: param, callback: callback });
	}

	//店铺信息
	$scope.goto_storeInfo = function (info) {
		$state.go('store-info', { storeInfo: $scope.storeInfo }, { reload: true });
	};

	//初始化店铺详情
	$scope.storeInfo_init = function () {
		$scope.isStop_scroll = true;
		$scope.currPage = 1;

		$scope.storeInfo = $stateParams.storeInfo;
		$scope.curr_store_id = $scope.storeInfo.id;
		console.log("店铺详情：");console.log($scope.storeInfo);
		$scope.load_store_comments($scope.storeInfo.id);
		$scope.store_tab_change("store_tab1");

	};



	//发送店铺评论
	$scope.store_comment = '';

	$scope.sent_store_comment = function () {
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var param = {
			shop_id: $scope.storeInfo.id,
			user_id: user.id,
			content: $scope.store_comment,
			imglist: []
		};
		console.log(JSON.stringify(param));

		var callback = {
			success: function success(result) {
				console.log("发送店铺评论返回：");
				console.log(result);
				$scope.store_comment = '';
				$scope.isStop_scroll = true;
				$scope.currPage = 1;
				//$scope.store_comments = result.result;
				$scope.load_store_comments($scope.storeInfo.id);
			}
		};

		HttpService({ name: 'shop/comment/create', params: param, callback: callback });
	};

	//查询点
	$scope.load_store_class = function (catId) {
		var param = {
			page: $scope.currPage_normal,
			category_id: catId,
			shop_id: $scope.storeInfo.id
		};
		$scope.product_data = [];
		$scope.load_product_list(param);
	};

	//跳转商品评论

	//商铺认证详情
	$scope.certi_content = '';
	$scope.goto_store_identify_info = function(content){
		$scope.certi_content = content;
		$scope.store_identify_modal.show();
	}

	$scope.call_store = function(tel){
		if(tel)
		$window.location.href="tel:"+tel;
	}

	/*--------店铺列表--END--------------------------------------------------------------------------------------------------------*/
});

/*商品件数插件*/
ionicTea.directive('countInput', function () {
	return {
		restrict: 'AE',
		scope: {},
		template: '<ul class="count-cont">' + '<li ng-click="decrement()">－</li><li><span></span></li><li ng-click="increment()">＋</li>' + '</ul>',
		require: 'ngModel',
		link: function link(scope, iElement, iAttrs, ngModelController) {

			function updateModel(offset) {
				ngModelController.$setViewValue(ngModelController.$viewValue + offset);
				ngModelController.$render();
			};

			ngModelController.$render = function () {
				iElement.find('span').text(ngModelController.$viewValue);
			};

			scope.decrement = function () {
				if (ngModelController.$viewValue >= 2) updateModel(-1);
			};
			scope.increment = function () {
				updateModel(+1);
			};
		}
	};
});

/*tab按钮插件*/
ionicTea.directive('slideX', function () {
	return {
		restrict: 'AE',
		template: '<ion-scroll direction="x" class="slide-bt-group"></ion-scroll>',
		link: function link(scope, iElement, iAttrs, ngModelController) {}
	};
});

ionicTea.directive('slideTab', function () {
	return {
		restrict: 'AE',
		scope: {
			tabs: '=',
			callback: '=',
		},
		template: function template(tElement, tAttrs) {
			var _html = '';
			_html += '<button class="bt-style2" id="slideItem{{item.id}}" ng-repeat="item in tabs" ng-click="active(item.id)">{{item.name}}</button>';
			_html += '';
			return _html;
		},
		controller: function controller() {},
		link: function link(scope, iElement, attr, ngModelController) {

			scope.active = function (id) {

				var items = iElement.find('button');
				var active_item = document.getElementById("slideItem" + id);

				for (var i = 0; i < items.length; i++) {
					var classStr = items[i].className;
					if (items[i] != active_item) {
						items[i].className = 'bt-style2';
					} else {
						active_item.className = classStr + ' bt-active2';
					}
				}
				scope.callback(id);

			};
		}
	};
});
